package com.afterRain.admin.controller;

import java.io.File;
import java.util.Date;

import com.afterRain.commonly.CommonlyRecord;
import com.afterRain.commonly.Prompt;
import com.afterRain.model.Admin;
import com.afterRain.util.FileUtil;
import com.afterRain.util.MD5Util;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;

/**
* @author 作者 E-mail:616352178
* @version 创建时间：2017年5月9日 上午11:39:54
* 类说明
*/
public class IndexController extends Controller{

	/**
	 * enter the home  page
	 */
	public void index(){
		render("index.ftl");
	}

	/**
	 * enter the user information page
	 */
	public void info(){
		render("user/info.ftl");
	}
	
	/**
	 * enter the user password page
	 */
	public void password(){
		render("user/password.ftl");
	}
	
	/**
	 * update user inforamation
	 */
	@Before(POST.class)
	public void userinfo(){
		//upload file
		UploadFile file = getFile("img","img");
		Admin admin = getBean(Admin.class, "");
		if( file != null){
			Admin admin1 = getSessionAttr(CommonlyRecord.SESSION_USER.name());
			String img = FileUtil.fileUploadRename(file,admin1.getAccount(),"img","",false);
			if(img == null){
				renderJson(Prompt.uploaderror);
				return ;
			}
			admin.setImgUrl(img);
		}
		//update database
		if(!admin.update()){
			renderJson(Prompt.saveerror);
			return ;
		}
		//update session data
		admin = Admin.dao.findById(admin.getId());
		setSessionAttr(CommonlyRecord.SESSION_USER.name(), admin);
		renderJson(Prompt.success);
	}
	
	/**
	 * update user password
	 */
	@Before(POST.class)
	public void updatePassword(){
		Admin admin1 = getSessionAttr(CommonlyRecord.SESSION_USER.name());
		//password don't match
		if(!admin1.getPassword().equals(MD5Util.getMD5(getPara("passwordyuan")))){
			renderJson(Prompt.pwderror);
			return ;
		}
		Admin admin = getBean(Admin.class, "");
		//password md5 encrypt
		admin.setPassword(MD5Util.getMD5(admin.getPassword()));
		//update database
		if(!admin.update()){
			renderJson(Prompt.saveerror);
			return ;
		}
		//remove session data
		removeSessionAttr(CommonlyRecord.SESSION_USER.name());
		renderJson(Prompt.success);
	}
}
